package com.ezbuy.common.helper;

import com.ezbuy.common.functions.Checker;

import java.io.File;
import java.io.FileReader;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class FileHelper {

    private static final String without_postfix = "([^<>/\\\\|:\"\"\\*\\?]+)\\.\\w+$+";
    private static final String with_postfix = "([^<>/\\\\\\|:\"\"\\*\\?]+\\.\\w+$)";

    /**
     * 读取文件
     *
     * @param in
     * @return
     */
    public static String readFile(File in) {
        if (!in.exists() && in.isDirectory()) {
            return "";
        }

        FileReader fr = null;
        try {
            fr = new FileReader(in);
            //字符数组循环读取
            char[] buf = new char[1024];
            int len = 0;
            StringBuilder sb = new StringBuilder();
            while ((len = fr.read(buf)) != -1) {
                sb.append(new String(buf, 0, len));
            }

            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static String getFileNameWithOutPostfix(String path) {
        Matcher m = Pattern.compile(without_postfix).matcher(path);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }

    public static String getFileNameWithPostfix(String path) {
        Matcher m = Pattern.compile(with_postfix).matcher(path);
        if (m.find()) {
            return m.group(1);
        }
        return "";
    }

    public static void traverseFolder(List<String> list, String dirPath, Checker<String> checker) {
        File dir = new File(dirPath);
        if (!dir.exists()) {
            System.out.println("文件不存在!");
            return;
        }
        File[] files = dir.listFiles();
        if (files.length == 0) {
            System.out.println("文件夹是空的!");
            return;
        }
        for (File file : files) {
            String path = file.getAbsolutePath();
            if (file.isDirectory()) {
//                System.out.println("文件夹:" + path);
                traverseFolder(list, path, checker);
            } else {
                if (checker.map(path)) {
//                    System.out.println("添加文件:" + path);
                    list.add(path);
                } else {
//                    System.out.println("文件不满足checker条件:" + path);
                }
            }
        }
    }
}
